package com.inmaytide.website.facade.deploy.impl;

import com.inmaytide.website.domain.entities.deploy.DeployInfo;
import com.inmaytide.website.domain.entities.deploy.DeployProject;
import com.inmaytide.website.domain.vo.deploy.DeployInfoVo;
import com.inmaytide.website.facade.deploy.DeployInfoFacade;
import com.inmaytide.website.framework.bean.JsonResult;
import com.inmaytide.website.service.deploy.DeployInfoService;
import com.inmaytide.website.service.deploy.DeployProjectService;
import com.inmaytide.website.utils.ZipUtil;
import com.inmaytide.website.utils.pagination.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;


@Service
public class DeployInfoFacadeImpl implements DeployInfoFacade {

    @Autowired
    private DeployInfoService deployInfoService;

    @Autowired
    private DeployProjectService deployProjectService;

    @Override
    public JsonResult deploy(DeployInfoVo info) {
        return deployInfoService.deploy(info);
    }

    @Override
    public List<DeployProject> findProjectsInUse() {
        return deployProjectService.findProjectsInUse();
    }

    @Override
    public List<DeployInfo> findList() {
        return deployInfoService.findAll();
    }

    @Override
    public JsonResult findOne(Long id) {
        try {
            DeployInfo info = deployInfoService.findOne(id);
            JsonResult result = new JsonResult(true, null);
            result.setProperty("info", info);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            JsonResult result = new JsonResult(false, e.getMessage());
            result.setProperty("info", new DeployInfo());
            return result;
        }
    }

    @Override
    public List<String> readZip(MultipartFile file) throws Exception {
        if (file.getSize() == 0)
            throw new Exception("文件为空!");

        try {
            InputStream is = file.getInputStream();
            List<ZipEntry> files = ZipUtil.readZip(is);
            if (files == null || files.isEmpty())
                throw new Exception("未读取到任何文件!");

            List<String> fileNames = new ArrayList<String>();
            for (ZipEntry entry : files) {
                fileNames.add(entry.getName());
            }
            return fileNames;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("文件读取失败!");
        }
    }

    /**
     * 分页
     *
     * @param request
     * @param pagination
     * @return
     */
    @Override
    public Pagination<DeployInfoVo> pagination(HttpServletRequest request, Pagination<DeployInfoVo> pagination) {
        return deployInfoService.pagination(request, pagination);
    }
}
